// "use client";
import { useState, useEffect } from "react";
import type { TableProps } from "antd";
import {
  Layout,
  theme,
  Table,
  Button,
  Input,
  Modal,
  Form,
  message,
  Card,
  Row,
  Col,
} from "antd";
import img from "./image.png";
import "./App12.css";
import CoolLineChart from "./CoolLineChart";
const { Header, Content, Sider } = Layout;

//表格数据
interface DataType {
  key: string;
  name: string;
  types: string;
  ri: string;
  ageA: string;
  ageB: string;
  address: string;
}

//趋势预测数据接口
interface TrendData {
  date: string;
  value: number;
  type: string;
}

//金额趋势数据接口
interface AmountTrendData {
  date: string;
  maxAmount: number;
  minAmount: number;
  name: string;
}

//表格数据
const data: DataType[] = [
  {
    key: "01",
    name: "北京",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥11,232,323",
    ageB: "￥3,233",
    address: "New York No. 1 Lake Park",
  },
  {
    key: "02",
    name: "上海",
    types: "异常",
    ri: "2025-07-09",
    ageA: "￥10,232,323",
    ageB: "￥5553",
    address: "London No. 1 Lake Park",
  },
  {
    key: "03",
    name: "天津",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥32,32,323",
    ageB: "￥3,333",
    address: "Sydney No. 1 Lake Park",
  },
  {
    key: "04",
    name: "重庆",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥6,232,323",
    ageB: "￥3,633",
    address: "Sydney No. 1 Lake Park",
  },
  {
    key: "05",
    name: "成都",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥4,232,323",
    ageB: "￥3,333",
    address: "Sydney No. 1 Lake Park",
  },
  {
    key: "06",
    name: "武汉",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥6,232,323",
    ageB: "￥2,333",
    address: "Sydney No. 1 Lake Park",
  },
  {
    key: "07",
    name: "西安",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥7,232,323",
    ageB: "￥3,243",
    address: "Sydney No. 1 Lake Park",
  },
  {
    key: "08",
    name: "兰州",
    types: "正常",
    ri: "2025-07-09",
    ageA: "￥3,232,323",
    ageB: "￥3,333",
    address: "Sydney No. 1 Lake Park",
  },
];

export default function Trendqushi() {
  //主题
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();
  //时间
  const [dateTime, setDateTime] = useState(new Date());
  //搜索功能
  const [searchText, setSearchText] = useState("");
  //表格数据
  const [allData, setAllData] = useState(data);
  //表格数据
  const [filteredData, setFilteredData] = useState(data);
  //新增编辑功能显示
  const [modalVisible, setModalVisible] = useState(false);
  //新增编辑功能显示
  const [editingRecord, setEditingRecord] = useState<DataType | null>(null);
  //新增编辑功能显示
  const [form] = Form.useForm();
  //趋势预测数据
  const [trendData, setTrendData] = useState<TrendData[]>([]);
  //金额趋势数据
  const [amountTrendData, setAmountTrendData] = useState<AmountTrendData[]>([]);

  //生成趋势预测数据
  const generateTrendData = () => {
    const historicalData: TrendData[] = [];
    const predictionData: TrendData[] = [];

    // 生成过去30天的历史数据
    for (let i = 29; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split("T")[0];
      const baseValue = 3000000;
      const randomVariation = (Math.random() - 0.5) * 500000;
      const trendFactor = Math.sin(i * 0.2) * 200000;
      const value = Math.max(0, baseValue + randomVariation + trendFactor);

      // 根据数值大小确定颜色分类
      let colorCategory = "正常";
      if (value > 3500000) colorCategory = "高值";
      else if (value < 2500000) colorCategory = "低值";

      historicalData.push({
        date: dateStr,
        value: Math.round(value),
        type: `历史数据-${colorCategory}`,
      });
    }

    // 生成未来15天的预测数据
    for (let i = 1; i <= 15; i++) {
      const date = new Date();
      date.setDate(date.getDate() + i);
      const dateStr = date.toISOString().split("T")[0];
      const lastHistoricalValue =
        historicalData[historicalData.length - 1].value;
      const trendSlope = 15000; // 上升趋势
      const randomVariation = (Math.random() - 0.5) * 300000;
      const value = Math.max(
        0,
        lastHistoricalValue + trendSlope * i + randomVariation
      );

      // 根据数值大小确定颜色分类
      let colorCategory = "正常";
      if (value > 3500000) colorCategory = "高值";
      else if (value < 2500000) colorCategory = "低值";

      predictionData.push({
        date: dateStr,
        value: Math.round(value),
        type: `预测数据-${colorCategory}`,
      });
    }

    setTrendData([...historicalData, ...predictionData]);
  };

  //生成金额趋势数据
  const generateAmountTrendData = () => {
    const amountData: AmountTrendData[] = allData.map((item, index) => {
      // 解析金额字符串，移除￥符号和逗号
      const maxAmountStr = item.ageA.replace(/[￥,]/g, "");
      const minAmountStr = item.ageB.replace(/[￥,]/g, "");
      const maxAmount = parseInt(maxAmountStr) || 0;
      const minAmount = parseInt(minAmountStr) || 0;
      // 生成日期序列
      const date = new Date();
      date.setDate(date.getDate() - (allData.length - index - 1));
      const dateStr = date.toISOString().split("T")[0];
      return {
        date: dateStr,
        maxAmount,
        minAmount,
        name: item.name,
      };
    });
    setAmountTrendData(amountData);
  };

  //表格行样式
  const tableHeaderStyle = {
    backgroundColor: "rgb(60, 103, 197)",
    color: "rgb(58, 173, 235)",
    fontWeight: "bold",
    fontSize: 16,
  };

  //表格行样式
  const components = {
    header: {
      cell: (props: any) => <th style={tableHeaderStyle}>{props.children}</th>,
    },
  };

  //搜索功能
  const handleSearch = () => {
    if (!searchText) {
      setFilteredData(allData);
    } else {
      setFilteredData(allData.filter((item) => item.name.includes(searchText)));
    }
  };

  //新增和编辑
  const handleOk = () => {
    form.validateFields().then((values: any) => {
      if (editingRecord) {
        const newData = allData.map((item) =>
          item.key === editingRecord.key
            ? { ...editingRecord, ...values }
            : item
        );
        setAllData(newData);
        setFilteredData(
          newData.filter((item) => item.name.includes(searchText))
        );
        message.success("编辑成功");
      } else {
        const newKey = Date.now().toString();
        const newItem = { ...values, key: newKey };
        const newData = [...allData, newItem];
        setAllData(newData);
        setSearchText("");
        setFilteredData(newData);
        message.success("新增成功");
      }
      setModalVisible(false);
    });
  };
  //新增编辑功能取消
  const handleCancel = () => {
    setModalVisible(false);
  };
  //表格行样式
  const rowClassName = () => "custom-table-row";
  //时间
  useEffect(() => {
    setDateTime(new Date());
  }, []);

  // 初始化趋势数据（仅首次加载）
  useEffect(() => {
    generateTrendData();
    generateAmountTrendData();
  }, []);

  //获取星期几
  const getWeekday = (date: Date) => {
    const weekDays = [
      "星期日",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六",
    ];
    return weekDays[date.getDay()];
  };

  // 刷新趋势预测数据
  const handleRefreshTrend = () => {
    generateTrendData();
    generateAmountTrendData();
    message.success("趋势预测数据已更新");
  };

  //表格列
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "序号",
      dataIndex: "key",
      key: "id",
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "日期",
      dataIndex: "ri",
      key: "ri",
    },
    {
      title: "状态",
      dataIndex: "types",
      key: "types",
    },
    {
      title: "最大金额",
      dataIndex: "ageA",
      key: "ageA",
    },
    {
      title: "最小金额",
      dataIndex: "ageB",
      key: "ageB",
    },

    {
      title: "内容",
      dataIndex: "address",
      key: "address",
    },
  ];
  // 统计数据
  const total = allData.length;
  const normalCount = allData.filter((item) => item.types === "正常").length;
  const abnormalCount = allData.filter((item) => item.types === "异常").length;
  const pieData = [
    { type: "正常", value: normalCount },
    { type: "异常", value: abnormalCount },
  ];

  // 趋势预测图表配置
  const trendConfig = {
    data: trendData,
    xField: "date",
    yField: "value",
    seriesField: "type",
    animation: {
      appear: {
        animation: "fade-in",
        duration: 1000,
      },
    },
    color: [
      "#52c41a", // 历史数据-正常 - 绿色
      "#1890ff", // 历史数据-高值 - 蓝色
      "#faad14", // 历史数据-低值 - 橙色
      "#13c2c2", // 预测数据-正常 - 青色
      "#ff4d4f", // 预测数据-高值 - 红色
      "#722ed1", // 预测数据-低值 - 紫色
    ],
    columnStyle: {
      radius: [4, 4, 0, 0],
    },
    tooltip: {
      shared: true,
      formatter: (datum: any) => {
        return {
          name: datum.type,
          value: `￥${datum.value.toLocaleString()}`,
        };
      },
    },
    legend: {
      position: "top",
    },
    xAxis: {
      type: "time",
      tickCount: 8,
    },
    yAxis: {
      label: {
        formatter: (value: string) =>
          `￥${(parseInt(value) / 1000000).toFixed(1)}M`,
      },
    },
    annotations: [
      {
        type: "line",
        start: ["min", "mean"],
        end: ["max", "mean"],
        style: {
          stroke: "#ff4d4f",
          lineDash: [2, 2],
        },
      },
    ],
  };

  // 金额趋势线型图配置（每个人一条线，最大金额）
  const multiLineData = allData.map((item) => ({
    date: item.ri, // 确保格式为 'YYYY-MM-DD'
    value: parseInt(item.ageA.replace(/[￥,]/g, "")) || 0, // 最大金额
    name: item.name,
  }));

  // 生成10日后的预测数据
  const generatePredictionData = () => {
    const predictionData: Array<{
      date: string;
      value: number;
      name: string;
      type: string;
    }> = [];

    // 为每个人员生成未来10天的预测数据
    allData.forEach((item) => {
      const currentValue = parseInt(item.ageA.replace(/[￥,]/g, "")) || 0;
      const currentDate = new Date(item.ri);

      // 生成未来10天的预测
      for (let i = 1; i <= 10; i++) {
        const futureDate = new Date(currentDate);
        futureDate.setDate(futureDate.getDate() + i);
        const dateStr = futureDate.toISOString().split("T")[0];

        // 预测逻辑：基于当前值，添加增长趋势和随机波动
        const growthRate = 0.02; // 每日2%的增长
        const randomFactor = 0.95 + Math.random() * 0.1; // 0.95-1.05的随机因子
        const predictedValue = Math.round(
          currentValue * Math.pow(1 + growthRate, i) * randomFactor
        );

        predictionData.push({
          date: dateStr,
          value: predictedValue,
          name: item.name,
          type: "预测数据",
        });
      }
    });

    return predictionData;
  };

  // 合并当前数据和预测数据
  const currentData = multiLineData.map((item) => ({
    ...item,
    type: "当前数据",
  }));
  const predictionData: any = generatePredictionData();
  const allLineData = [...currentData, ...predictionData];

  // 移除测试数据，只使用表格中的真实数据
//   console.log("multiLineData (表格数据)", multiLineData); // 调试输出
//   console.log("predictionData (预测数据)", predictionData); // 调试输出
//   console.log("allLineData (全部数据)", allLineData); // 调试输出

  // 获取所有唯一的人员名称并排序
  const uniqueNames = Array.from(
    new Set(multiLineData.map((d) => d.name))
  ).sort();
//   console.log("uniqueNames", uniqueNames); // 调试输出
  //     data: allLineData, // 使用当前数据+预测数据
  //     xField: 'date',
  //     yField: 'value',
  //     seriesField: 'name',
  //     colorField: 'name', // 添加colorField
  //     smooth: false,
  //     animation: false,
  //     color: [
  //         '#ff4d4f', // 红色
  //         '#1890ff', // 蓝色
  //         '#52c41a', // 绿色
  //         '#faad14', // 橙色
  //         '#722ed1', // 紫色
  //         '#13c2c2', // 青色
  //         '#eb2f96', // 粉色
  //         '#fa8c16', // 深橙色
  //     ],
  //     theme: {
  //         colors10: [
  //             '#ff4d4f', '#1890ff', '#52c41a', '#faad14',
  //             '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16'
  //         ],
  //         axis: {
  //             label: {
  //                 style: {
  //                     fill: 'rgba(255,255,255,1)',
  //                     fontSize: 36,
  //                     fontWeight: 'bold',
  //                     textShadow: '1px 1px 2px #000',
  //                 }
  //             },
  //             title: {
  //                 style: {
  //                     fill: 'rgba(255,255,255,1)',
  //                     fontSize: 36,
  //                     fontWeight: 'bold',
  //                     textShadow: '2px 2px 4px #000',
  //                 }
  //             }
  //         }
  //     },
  //     point: {
  //         size: 40,
  //     },
  //     tooltip: {
  //         showCrosshairs: false,
  //     },
  //     legend: {
  //         position: 'top',
  //         itemName: {
  //             style: {
  //                 fontSize: 36,
  //                 fontWeight: 'bolder',
  //                 fill: 'rgba(255,255,255,1)',
  //                 textShadow: '3px 3px 8px #000, 0 0 8px #fff',
  //             },
  //         },
  //     },
  //     xAxis: {
  //         // type: 'cat',
  //         title: {
  //             text: '日期',
  //             style: {
  //                 fontSize: 36,
  //                 fontWeight: 'bolder',
  //                 fill: 'rgba(255,255,255,1)',
  //                 textShadow: '3px 3px 8px #000, 0 0 8px #fff',
  //             },
  //         },
  //         line: {
  //             style: {
  //                 stroke: '#ffd700',
  //                 lineWidth: 40,
  //             },
  //         },
  //         tickLine: {
  //             style: {
  //                 stroke: '#ffd700',
  //                 lineWidth: 50,
  //             },
  //         },
  //         label: {
  //             style: {
  //                 fontSize: 36,
  //                 fontWeight: 'bolder',
  //                 fill: 'rgba(255,255,255,1)',
  //                 textShadow: '3px 3px 8px #000, 0 0 8px #fff',
  //             },
  //         },
  //     },
  //     yAxis: {
  //         title: {
  //             text: '金额',
  //             style: {
  //                 fontSize: 36,
  //                 fontWeight: 'bolder',
  //                 fill: 'rgba(255,255,255,1)',
  //                 textShadow: '3px 3px 8px #000, 0 0 8px #fff',
  //             },
  //         },
  //         line: {
  //             style: {
  //                 stroke: '#ffd700',
  //                 lineWidth: 40,
  //             },
  //         },
  //         tickLine: {
  //             style: {
  //                 stroke: '#ffd700',
  //                 lineWidth: 30,
  //             },
  //         },
  //         label: {
  //             formatter: (value: string) => `￥${(parseInt(value) / 1000000).toFixed(1)}M`,
  //             style: {
  //                 fontSize: 36,
  //                 fontWeight: 'bolder',
  //                 fill: 'rgba(255,255,255,1)',
  //                 textShadow: '3px 3px 8px #000, 0 0 8px #fff',
  //             },
  //         },
  //     },
  // };

  // 组装 ECharts 所需数据
  const xData = Array.from(new Set(allLineData.map((d) => d.date))).sort();
  const names = Array.from(new Set(allLineData.map((d) => d.name)));
  const seriesData = names.map((name, idx) => ({
    name,
    data: xData.map((date) => {
      const found = allLineData.find((d) => d.name === name && d.date === date);
      return found ? found.value : null;
    }),
  }));

  return (
    <Layout style={{ height: "80%" }}>
      <Sider width={400} style={{ background: colorBgContainer }}>
        {/* 侧边栏图片 */}
        <img
          src={img}
          alt="侧边栏图片"
          style={{ width: "100%", height: "100%" }}
        />
      </Sider>
      {/* 内容 */}
      <Layout
        style={{
          backgroundColor: "rgb(26, 59, 116)",
          padding: "0 24px 24px",
          // overflow: "scroll",
        }}
      >
        {/* 内容 */}
        <Content
          style={{
            padding: 24,
            margin: 0,
            minHeight: "calc(100vh - 200px)", // 调整为基于视口高度的计算值
            minWidth: 800,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
            backgroundColor: "rgb(39, 87, 169)",
            overflow: "auto", // 确保溢出时显示滚动条
          }}
        >
          {/* 标题名称 */}
          <div className="sd">最大金额趋势预测分析</div>

          {/* 趋势预测图表 */}

          <div style={{ marginTop: 16, color: "#fff" }}>
            {" "}
            <Card
              title=""
              extra={
                <Button type="primary" onClick={handleRefreshTrend}>
                  刷新预测
                </Button>
              }
              style={{
                marginBottom: 34,
                backgroundColor: "rgb(43, 88, 166)",
                border: "1px solid rgb(60, 103, 197)",
              }}
            >
              <div
                style={{
                  height: 500,
                  padding: "16px",
                  borderRadius: "18px",
                }}
              >
                <CoolLineChart xData={xData} seriesData={seriesData} />
              </div>
              <div style={{ marginTop: 16, color: "#fff" }}>
                <Row gutter={16}>
                  <Col span={8}>
                    <div style={{ color: "#fff" }}>
                      当前数据点: {currentData.length}
                    </div>
                  </Col>
                  <Col span={8}>
                    <div style={{ color: "#fff" }}>
                      预测数据点: {predictionData.length}
                    </div>
                  </Col>
                  <Col span={8}>
                    <div style={{ color: "#fff" }}>
                      最大金额: ￥
                      {allLineData.length > 0
                        ? Math.max(
                            ...allLineData.map((d) => d.value)
                          ).toLocaleString()
                        : "0"}
                    </div>
                  </Col>
                  <Col span={8}>
                    <div style={{ color: "#fff" }}>
                      地区数:{" "}
                      {
                        Array.from(new Set(allLineData.map((d) => d.name)))
                          .length
                      }
                    </div>
                  </Col>
                </Row>
                <Row gutter={16} style={{ marginTop: 8 }}>
                  <Col span={24}>
                    <div
                      style={{
                        fontSize: "12px",
                        opacity: 0.8,
                        color: "#fff",
                      }}
                    >
                      每条线代表地区最大金额的变化趋势，包含当前数据和未来10天预测
                    </div>
                  </Col>
                </Row>
              </div>
            </Card>
          </div>

          {/* 搜索 */}
          <div>
            {/* 搜索 */}
            <div className="ss">
              <Input
                width={300}
                type="text"
                placeholder="请输入名称"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 200, marginRight: 8 }}
              />
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
            </div>
          </div>
          {/* 表格 */}
          <Table<DataType>
            rowHoverable={false}
            style={{ backgroundColor: "rgb(43, 88, 166)" }}
            columns={columns}
            dataSource={filteredData}
            components={components}
            rowClassName={rowClassName}
            pagination={{ pageSize: 3, showSizeChanger: true }}
          />
          {/* 新增编辑功能 */}
          <Modal
            title={editingRecord ? "编辑" : "新增"}
            open={modalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            {/* 表单 */}
            <Form form={form} layout="vertical">
              <Form.Item
                label="名称"
                name="name"
                rules={[{ required: true, message: "请输入名称" }]}
              >
                {" "}
                <Input />{" "}
              </Form.Item>
              <Form.Item
                label="日期"
                name="ri"
                rules={[{ required: true, message: "请输入日期" }]}
              >
                {" "}
                <Input />{" "}
              </Form.Item>
              <Form.Item
                label="状态"
                name="types"
                rules={[{ required: true, message: "请输入状态" }]}
              >
                {" "}
                <Input />{" "}
              </Form.Item>
              <Form.Item
                label="最大金额"
                name="ageA"
                rules={[{ required: true, message: "请输入最大金额" }]}
              >
                {" "}
                <Input />{" "}
              </Form.Item>
              <Form.Item
                label="最小金额"
                name="ageB"
                rules={[{ required: true, message: "请输入最小金额" }]}
              >
                {" "}
                <Input />{" "}
              </Form.Item>
              <Form.Item
                label="内容"
                name="address"
                rules={[{ required: true, message: "请输入内容" }]}
              >
                {" "}
                <Input />{" "}
              </Form.Item>
            </Form>
          </Modal>
        </Content>
      </Layout>
    </Layout>
  );
}
